import {
  Controller,
  Get,
  Param,
  Delete,
  Patch,
  Body,
  Req,
  ParseIntPipe,
  Query,
  DefaultValuePipe,
  Post
} from '@nestjs/common'
import { FileService } from './file.service'
import { Request } from 'express'
import { RenameFileDto } from './dto/file.dto'
import { CreateFolderDto } from './dto/createFolder.dto'

@Controller('files')
export class FileController {
  constructor(private readonly fileService: FileService) {}

  @Get()
  async getUserFiles(
    @Req() req: Request,
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
    @Query('size', new DefaultValuePipe(10), ParseIntPipe) size: number,
    @Query('filename') filename?: string,
    @Query('filetype') filetype?: string,
    @Query('parentId') parentId?: number
  ) {
    const userId = req['user'].sub
    return this.fileService.getUserFiles(
      userId,
      page,
      size,
      filename,
      filetype,
      parentId
    )
  }

  @Get(':id')
  async getFileDetails(
    @Param('id', ParseIntPipe) fileId: number,
    @Req() req: Request
  ) {
    const userId = req['user'].sub
    return this.fileService.getFileDetails(fileId, userId)
  }

  @Delete(':id')
  async deleteFile(
    @Param('id', ParseIntPipe) fileId: number,
    @Req() req: Request
  ) {
    const userId = req['user'].sub
    return this.fileService.deleteFile(fileId, userId)
  }

  @Patch(':id/rename')
  async renameFile(
    @Param('id', ParseIntPipe) fileId: number,
    @Body() renameFileDto: RenameFileDto,
    @Req() req: Request
  ) {
    const userId = req['user'].sub
    return this.fileService.renameFile(fileId, renameFileDto.filename, userId)
  }

  @Post('folder')
  async createFoler(
    @Body() createFolderDto: CreateFolderDto,
    @Req() req: Request
  ) {
    const userId = req['user'].sub
    return this.fileService.createFolder(
      createFolderDto.filename,
      userId,
      createFolderDto.parentId
    )
  }
}
